<template>
  <div class="app-container">
    <!--表单查询区-->
    <div class="filter-container">
      <el-input v-model="listQuery.key" placeholder="管理员名" style="width: 200px; margin-right: 10px" class="filter-item" clearable @keyup.enter.native="handleFilter" @clear="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        创建订单
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        批量导出
      </el-button>
    </div>

    <!--表格区-->
    <el-table
      v-loading="listLoading"
      :data="list"
      row-key="id"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="订单号" align="center" min-width="330">
        <template v-slot="{row}">
          <el-button type="text" @click="$router.push({ path: '/order/info', query: { code: row.code } })">{{ row.code }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="课程名" prop="courseName" align="center" min-width="150" />
      <el-table-column label="学生名" align="center" min-width="150">
        <template v-slot="{row}">
          <template v-if="row.edit">
            <!--行内修改学员信息-->
            <el-input v-model="row.studentName" class="edit-input" size="small" />
          </template>
          <span v-else>{{ row.studentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" width="130">
        <template v-slot="{row}">
          <template v-if="row.edit">
            <!--行内修改学员信息-->
            <el-input v-model="row.phone" class="edit-input" size="small" />
          </template>
          <span v-else>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单总价" prop="totalPrice" align="center" min-width="80" />
      <el-table-column label="订单状态" prop="state" align="center" width="100">
        <template v-slot="{row}">
          <el-tag v-if="row.state === 0" type="success">已支付</el-tag>
          <el-tag v-else-if="row.state === 1">待付款</el-tag>
          <el-tag v-else-if="row.state === 2" type="danger">已退款</el-tag>
          <el-tag v-else-if="row.state === 3" type="info">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="210">
        <template v-slot="{row}">
          <el-button
            v-if="row.edit"
            class="cancel-btn"
            size="small"
            type="warning"
            @click="cancelEdit(row)"
          >
            取消
          </el-button>
          <el-button v-if="row.edit" type="success" size="mini" @click="confirmEdit(row)">
            确认
          </el-button>
          <el-button v-else type="primary" size="mini" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页插件-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />

  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { getOrderPage, getOrderList, updateOrderStudent, delByOrderCode } from '@/api/order'
import { parseTime } from '@/utils'

export default {
  name: 'Index',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      // 订单列表
      list: [],
      // 总数
      total: 0,
      // 表格渲染标志
      listLoading: true,
      // 查询对象
      listQuery: {
        current: 1,
        size: 20,
        key: ''
      },
      // 表单数据
      temp: {
        id: undefined,
        realName: '',
        phone: ''
      },
      // 表单对话框状态控制 true显示  false隐藏
      dialogFormVisible: false,
      // 下载加载
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 分页获取订单列表
    getList() {
      // 开启加载渲染
      this.listLoading = true
      getOrderPage(this.listQuery).then(res => {
        const items = res.data.records
        this.total = res.data.total
        // 像数据中添加变量
        this.list = items.map(v => {
          this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
          // 用户点击取消时回复初始值
          v.originPhone = v.phone
          v.originStudentName = v.studentName
          return v
        })
        // 关闭加载渲染
        this.listLoading = false
      }).catch(() => {
        // 请求错误，关闭加载渲染
        this.listLoading = false
      })
    },
    // 搜索处理函数
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    // 添加订单
    handleCreate() {
      this.$router.push('/order/add')
    },
    // 编辑订单学员信息
    handleEdit(order) {
      order.edit = true
      order.originPhone = order.phone
      order.originStudentName = order.studentName
    },
    // 取消修改学员信息
    cancelEdit(order) {
      order.phone = order.originPhone
      order.studentName = order.originStudentName
      order.edit = false
    },
    // 确认修改学员信息
    confirmEdit(order) {
      const data = {
        id: order.studentId,
        realName: order.studentName,
        phone: order.phone
      }
      updateOrderStudent(data).then(res => {
        this.$notify.success({
          title: '成功',
          message: res.msg,
          duration: 2000
        })
        order.originStudentName = order.studentName
        order.originPhone = order.phone
        order.edit = false
      })
    },
    // 删除订单信息
    handleDelete(order) {
      this.$confirm('此操作将永久删除该订单，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delByOrderCode(order.code).then(res => {
          this.$notify.success({
            title: '成功',
            message: res.data,
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
        this.$notify.info({
          title: '提示',
          message: '已取消删除',
          duration: 2000
        })
      })
    },
    // 批量导出处理
    handleDownload() {
      this.downloadLoading = true
      getOrderList().then(res => {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['序号', '订单编号', '课程名', '学员名', '手机号', '订单总价', '订单状态', '创建时间', '支付时间', '退款时间']
          const filterVal = ['id', 'code', 'courseName', 'studentName', 'phone', 'totalPrice', 'state', 'createTime', 'payTime', 'refundTime']
          const data = this.formatJson(filterVal, res.data)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '订单列表' + parseTime(new Date(), '{y}-{m}-{d}-{h}-{i}-{s}')
          })
          this.downloadLoading = false
        })
      })
    },
    // 格式化下载数据
    formatJson(filterVal, list) {
      return list.map(v => filterVal.map(j => {
        if (j === 'createTime' || j === 'payTime' || j === 'refundTime') {
          return parseTime(v[j])
        } else if (j === 'state') {
          if (v[j] === 0) {
            return '已付款'
          } else if (v[j] === 1) {
            return '待支付'
          } else {
            return '已退款'
          }
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style scoped>

</style>
